<template>
	<el-card class="form-container">
		<el-form :model="dataForm" ref="dataForm" :rules="dataRule" @keyup.enter.native="dataFormSubmitHandle()" label-width="90px">
			<el-form-item label="部门名称" prop="deptName">
				<el-input v-model="dataForm.deptName" placeholder="请输入部门名称"></el-input>
			</el-form-item>
			<el-form-item label="上级部门" prop="parentCode">
				<treeselect
					v-model="dataForm.parentCode"
					:options="deptOptions"
					:normalizer="normalizer"
					:show-count="true"
					placeholder="选择上级部门"
				/>
			</el-form-item>
			<el-form-item label="部门排序" prop="deptSort">
				<el-input v-model="dataForm.deptSort" placeholder="请输入部门排序"></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="delFlag">
				<el-radio-group v-model="dataForm.delFlag">
					<el-radio :label="1">正常</el-radio>
					<el-radio :label="2">停用</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item>
				<el-button @click="cancel">取消</el-button>
				<el-button type="primary" @click="submit('dataForm')">确定</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
	import { addSystemDept ,findSystemDeptTree} from '@/api/admin/systemDept'
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	export default {
		name: 'add-systemDept',
		data() {
			return {
				deptOptions:[],
				dataForm: {
					deptName: '',
					parentCode: null,
					parentName: '',
					deptSort: '',
					delFlag: 1
				},
				dataRule: {
					deptName: [{
							required: true,
							message: '请输入部门名称',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 20,
							message: '长度在 3 到 20 个字符',
							trigger: 'blur'
						}
					],
					parentCode: [{
							required: true,
							message: '请输入上级部门编号',
							trigger: 'blur'
						},
					],
				}
			}
		},
		created() {
			this.dataForm.parentCode = this.$route.query.parentCode
			this.initDeptTree()
		},
		components:{
			Treeselect
		},
		methods: {
			initDeptTree(){
				findSystemDeptTree().then(response =>{
					this.deptOptions = [];
					const dept = { code: 0, deptName: '主类目', children: [] };
					dept.children = this.handleTree(response.data.responseData, "code");
					this.deptOptions.push(dept);
				})
			},
			/** 转换菜单数据结构 */
			normalizer(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.code,
					label: node.deptName,
					children: node.children
				};
			},
			cancel() {
				this.$router.go(-1)
			},
			submit() {
				const set = this.$refs;
				set['dataForm'].validate((valid) => {
					if (!valid) {
						return false
					}
					addSystemDept(this.dataForm).then(() => {
						this.$notify({
							title: '添加成功',
							message: '添加成功',
							type: 'success',
							duration: 2000,
							onClose: this.$router.go(-1)
						})
					})
				})
			}
		}
	}
</script>

<style>
</style>
